#include <bmDocument/Group.h>

namespace bmDoc
{
    Group::Group( const std::string &label )
        : Element ( label )
    {

    }

    void Group::addChild( Element *lpElement )
    {
        _children.push_back( lpElement );
        lpElement->setParent( this );
    }

    void Group::removeChild( Element *lpElement )
    {
        unsigned int index = getChildIndex ( lpElement );
        removeChild( index, 1 );
        //lpElement->setParent ( NULL );        
    }

    void Group::removeChild( unsigned int index, unsigned int count )
    {
        if ( index >= _children.size() )
        {
            return;
        }
        unsigned int maxPos = index + count;
        if ( maxPos > _children.size() )
        {
            maxPos = _children.size();
        }
        for ( unsigned int i = index; i < maxPos; i ++ )
        {
            _children[i]->setParent(NULL);
        }


        _children.erase(_children.begin() + index, _children.begin() + maxPos - index);
    }

    unsigned int Group::getChildIndex( Element *lpElement )
    {
        for ( ElementVector::iterator it = _children.begin(); it != _children.end(); it ++ )
        {
            if ( (*it).get() == lpElement )
            {
                return it - _children.begin();
            }
        }


        return _children.size();
    }
}
